package com.hu.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hu.common.BaseResponse;
import com.hu.common.ResultUtils;
import com.hu.constant.RedisConstant;
import com.hu.service.LikesService;
import com.hu.utils.RedisCacheHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user/")
@Slf4j
@RequiredArgsConstructor
public class LikesController {

    private final LikesService likesService;
    private final RedisCacheHelper redisCacheHelper;

    /**
     * 点赞存入redis
     * @param questionId
     * @return
     */
    @PostMapping("/add/like/{questionId}")
    public BaseResponse<Long> addLike(@PathVariable("questionId") Long questionId){
        long loginId = StpUtil.getLoginIdAsLong();
        String userQuestionLikeRedisKey = RedisConstant.getUserQuestionLikeRedisKey(questionId);
        return ResultUtils.success(redisCacheHelper.sSet(userQuestionLikeRedisKey,loginId));
    }

    /**
     * 判断当前用户是否点赞了该题目
     * 优化 ==> 使用 Redis TODO 先放在这里
     * 优化 ==> TODO 使用 bit，连续性
     * @param questionId
     * @return
     */
    @GetMapping("/islike/{questionId}")
    public BaseResponse<Boolean> isLike(@PathVariable("questionId") Long questionId) {
        // TODO NotLoginException
        long loginId = StpUtil.getLoginIdAsLong();
        String userQuestionLikeRedisKey = RedisConstant.getUserQuestionLikeRedisKey(questionId);
        Set<Object> objectSet = redisCacheHelper.sGet(userQuestionLikeRedisKey);
        // 先从redis中获取
        if (CollectionUtil.isNotEmpty(objectSet)){
            List<Long> userIds = objectSet.stream().filter(Long.class::isInstance).map(Long.class::cast).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(userIds) && userIds.contains(loginId)){
                return ResultUtils.success(Boolean.TRUE);
            }
        }
        // 获取失败，从db中获取
        boolean isLike = likesService.isLikes(loginId,questionId);
        return ResultUtils.success(Boolean.valueOf(isLike));
    }

    /**
     * 获取当前用户点赞的所有题目
     * @return
     */
    @GetMapping("/likes")
    public BaseResponse<Boolean> likes() {
        long loginId = StpUtil.getLoginIdAsLong();
        List<Long> questionIds = likesService.getProductIdsByUserId(loginId);
        // TODO 获取question
        return ResultUtils.success(Boolean.valueOf(true));
    }


}
